package com.applink.sell_proof;

import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.Stack;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.ViewStub;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.applink.sell_proof.api.DataHelper;
import com.applink.sell_proof.api.DataResult;
import com.applink.sell_proof.api.Methods;
import com.applink.sell_proof.constant.Constant;
import com.applink.sell_proof.fragment.QuestionFragment;
import com.applink.sell_proof.util.Utility;

public class QuizDetail extends BaseActionBarActivity implements Observer,RadioGroup.OnCheckedChangeListener{

	protected Stack<Long> mQuestionStack;
	protected List<Long> mQuestionIds;
	protected long mQuizId;
	protected final int MILESTONE_POINT = 5;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.quiz_detail);
		mQuizId = getIntent().getLongExtra(Constant.KEY_QUIZ_ID, -1);
		setTitle(getString(R.string.quiz_detail));
		mQuestionStack = new Stack<Long>();
		DataHelper.getInstance().addObserver(this);
		DataHelper.getInstance().getQuizDetail(mQuizId);
	}
	
	
	@Override
	protected void onPause() {
		super.onPause();
		DataHelper.getInstance().deleteObserver(this);
	}
	
	@Override
	public void update(Observable observable, Object data) {
		if(data == null) return;
		DataResult result = (DataResult) data;
		
		if(result.getMethodName() == Methods.getQuizDetail) {
			findViewById(R.id.loading_page).setVisibility(View.GONE);
			if(result.getErrorCode() == null) {
				mQuestionIds = (List<Long>) result.getData();
				if(mQuestionIds != null && mQuestionIds.size() > 0) {
					buildIndicatorQuestion(mQuestionIds.size());
					nextQuestion();
				}
			} else {
				//false
				DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case Dialog.BUTTON_NEGATIVE:
							dialog.dismiss();
							break;
						default:
							break;
						}
					}
				};
				showAlertDialog(listener,"Answer Quiz","Close",null,result.getErrorCode().toString(), true);
			}
			
		}if (result.getMethodName() == Methods.replyQuiz) {
			hideProgressDialog();
			if(result.getErrorCode() != null) {
				//false
				DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case Dialog.BUTTON_NEGATIVE:
							dialog.dismiss();
							break;
						default:
							break;
						}
					}
				};
				showAlertDialog(listener,"Answer Quiz","Close",null,getString(R.string.msg_quiz_submit_failed), true);
			} else {
				DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case Dialog.BUTTON_NEGATIVE:
							finish();
							break;
						default:
							break;
						}
					}
				};
				Utility.checkQuiz = true;
				showAlertDialog(listener,"Answer Quiz","Close",null,getString(R.string.msg_quiz_submit_successful), false);
			}

		}
		
	}
	
	public void nextQuestion() {
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
		long nextQuestionId = mQuestionIds.get(mQuestionStack.size());
		Fragment nextFragment =  getQuestionFragment(nextQuestionId);
		transaction.replace(R.id.quiz_container, nextFragment);
		transaction.commit();
		mQuestionStack.push(nextQuestionId);
		if(mQuestionIds.size() > MILESTONE_POINT) {
			String currentPosition = Integer.toString(mQuestionStack.size());
			String maxPosition = Integer.toString(mQuestionIds.size());
			((TextView)findViewById(R.id.page_index)).setText(String.format("%s/%s",currentPosition,maxPosition));
		} else {
			RadioGroup group = (RadioGroup) findViewById(R.id.dot_indicator);
			((RadioButton)group.getChildAt((mQuestionStack.size()-1))).setChecked(true);
		}
		
	}
	
	public void backQuestion(){
		mQuestionStack.pop();
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
		long previousQuestionId = mQuestionStack.peek();
		Fragment nextFragment =  getQuestionFragment(previousQuestionId);
		transaction.replace(R.id.quiz_container, nextFragment);
		transaction.commit();
		if(mQuestionIds.size() > MILESTONE_POINT) {
			String currentPosition = Integer.toString(mQuestionStack.size());
			String maxPosition = Integer.toString(mQuestionIds.size());
			((TextView)findViewById(R.id.page_index)).setText(String.format("%s/%s",currentPosition,maxPosition));
		} else {
			RadioGroup group = (RadioGroup) findViewById(R.id.dot_indicator);
			((RadioButton)group.getChildAt((mQuestionStack.size()-1))).setChecked(true);
		}
	}
	
	public boolean isFirstPager(){
		return mQuestionStack.size() == 1;
	}
	
	public boolean isLastPager() {
		return mQuestionStack.size() == mQuestionIds.size();
	}
	
	public long getQuiizId() {
		return mQuizId;
	}
	
	public void replyQuiz(){
		DataHelper.getInstance().replyQuiz(mQuizId);
		showProgressDialog(true);
	}
	
	private void buildIndicatorQuestion(int quantity) {
		ViewStub stub = (ViewStub) findViewById(R.id.question_indicator_stub);
		if(stub == null) return;// because stub resource already inflated.
		if(quantity > MILESTONE_POINT) {
			stub.setLayoutResource(R.layout.question_indicator_text);
			stub.inflate();
		} else {
			stub.setLayoutResource(R.layout.question_indicator_dot);
			stub.inflate();
			RadioGroup group = (RadioGroup) findViewById(R.id.dot_indicator);
			group.setOnCheckedChangeListener(this);
			for(int i = 0; i < quantity;i++) {
				RadioButton radioOption = new RadioButton(this);
				radioOption.setTag(i);
				radioOption.setButtonDrawable(R.drawable.btn_radio_holo);
				group.addView(radioOption);
			}
		}
	}


	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		RadioButton selectedButton = (RadioButton) group.findViewById(checkedId);
		int index = (Integer) selectedButton.getTag();
		long currentQuestionId = mQuestionStack.peek();
		if(currentQuestionId == mQuestionIds.get(index)) return;
		
		mQuestionStack.clear();
		for(int i = 0; i <=index;i++) {
			mQuestionStack.push(mQuestionIds.get(i));
		}
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
		Fragment currentFragment = getQuestionFragment(mQuestionIds.get(index));
		transaction.replace(R.id.quiz_container, currentFragment);
		transaction.commit();
	}
	
	protected Fragment getQuestionFragment(long questionId) {
		return QuestionFragment.newInstance(questionId);
	}
}
